package com.khyr.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.khyr.dao.*;
import com.khyr.entity.*;
import com.khyr.service.HealthService;
import com.khyr.vo.GetTestResultVo;
import com.khyr.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author ：Zhang
 * @date ：Created in 2025/3/18 20:35
 * @description：健康测试实现
 * @modified By：
 * @version: 1.0
 */
@Service
public class HealthServiceImpl implements HealthService {
    @Autowired
    private HealthPatientResultItemDao healthPatientResultItemDao;
    @Autowired
    private HealthPatientResultDao healthPatientResultDao;
    @Autowired
    private HealthTestResultDao healthTestResultDao;
    @Autowired
    private HealthTestDetailDao healthTestDetailDao;
    @Autowired
    private HealthTestListDao healthTestListDao;
    /**
     * @create by: Zr
     * @description: 获取所有的健康测试的信息
     * @create time: 2025/3/18 20:56
     * @param
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.HealthTestList>>
     */
    @Override
    public R<List<HealthTestList>> getAllHealthTest() {
        List<HealthTestList> list = healthTestListDao.selectList(null);
        if (list != null && list.size() > 0) {
            return new R<>(200, "查询成功", list);
        } else {
            return new R<>(500, "查询失败", null);
        }
    }
    /**
     * @create by: Zr
     * @description: 根据健康测试的主键id查询健康测试的详情（题目）
     * @create time: 2025/3/18 20:57
     * @param htId
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.HealthTestDetail>>
     */
    @Override
    public R<List<HealthTestDetail>> getHealthTestById(String htId) {
        QueryWrapper<HealthTestDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ht_id", htId);
        List<HealthTestDetail> list = healthTestDetailDao.selectList(queryWrapper);
        if (list != null && list.size() > 0) {
            return new R<>(200, "查询成功", list);
        } else {
            return new R<>(500, "查询失败", null);
        }
    }
    /**
     * @create by: Zr
     * @description: 抑郁测试结果 or 情商（EQ）测试结果,传入的参数中有题目分数，根据所有题目分数获得测试结果
     * @create time: 2025/3/19 11:19
     * @param healthTestDetails
     * @param patient
     * @return com.khyr.vo.R<com.khyr.vo.GetTestResultDto>
     */
    @Override
    public R<GetTestResultVo> getTestResult(List<HealthTestDetail> healthTestDetails, HisPatient patient) {
        // 1. 获取测试 题目
        String htId = healthTestDetails.get(0).getHtId();

        // 查询 所有的 测试结果
        QueryWrapper<HealthTestResult> healthTestResultQueryWrapper = new QueryWrapper<>();
        healthTestResultQueryWrapper.eq("ht_id",htId);
        HealthTestResult one = healthTestResultDao.selectOne(healthTestResultQueryWrapper);

        // 2. 将测试结果返回添加到数据库 health_patient_result
        HealthPatientResult healthPatientResult = new HealthPatientResult();
        String id = "PR"+ IdUtil.getSnowflakeNextId();
        healthPatientResult.setPrId(id);
        healthPatientResult.setHtId(htId);

        healthPatientResult.setHtTime(new Date());

        //计算出结果
        Integer score = 0;
        for (HealthTestDetail testResult : healthTestDetails){
            score += Integer.parseInt(testResult.getHtResult());
        }
        // 根据计算结果 返回对应的 测试结果
        if (score >= 0 && score < 4){
            healthPatientResult.setHtResTitle(one.getATitle());
            healthPatientResult.setHtResContent(one.getResA());
        }else if (score > 5 && score < 10){
            healthPatientResult.setHtResTitle(one.getBTitle());
            healthPatientResult.setHtResContent(one.getResB());
        } else if (score > 10 && score <= 20) {
            healthPatientResult.setHtResTitle(one.getCTitle());
            healthPatientResult.setHtResContent(one.getResC());
        } else if (score > 20 && score <= 25) {
            healthPatientResult.setHtResTitle(one.getDTitle());
            healthPatientResult.setHtResContent(one.getResD());
        } else if (score > 25 && score <= 30) {
            healthPatientResult.setHtResTitle(one.getETitle());
            healthPatientResult.setHtResContent(one.getResE());
        }
        // 拿到患者手机号 根据手机号 查询患者id
        healthPatientResult.setPatientId(patient.getPatientId());
        healthPatientResultDao.insert(healthPatientResult);
        // 3. 将测试结果添加到数据库  health_patient_result_item
        for (HealthTestDetail testResult : healthTestDetails) {
            if("0".equals(testResult.getHtResult())){
                HealthPatientResultItem healthPatientResultItem =
                        new HealthPatientResultItem(null,patient.getPatientId(),testResult.getId(),"不是",id);
                healthPatientResultItemDao.insert(healthPatientResultItem);
            }else {
                HealthPatientResultItem healthPatientResultItem =
                        new HealthPatientResultItem(null,patient.getPatientId(),testResult.getId(),"是的",id);
                healthPatientResultItemDao.insert(healthPatientResultItem);
            }

        }
        GetTestResultVo getTestResultVo = new GetTestResultVo();
        getTestResultVo.setTestResultTitle(healthPatientResult.getHtResTitle());
        getTestResultVo.setTestResult(healthPatientResult.getHtResContent());
        return new R<>(200, "查询成功", getTestResultVo);

    }
    /**
     * @create by: Zr
     * @description: FPA性格色彩测试结果
     * @create time: 2025/3/19 11:35
     * @param healthTestDetails
     * @param patient
     * @return com.khyr.vo.R<com.khyr.vo.GetTestResultDto>
     */
    @Override
    public R<GetTestResultVo> getTestResultFPA(List<HealthTestDetail> healthTestDetails, HisPatient patient) {
        // 1. 获取测试 题目
        String htId = healthTestDetails.get(0).getHtId();

        // 查询 所有的 测试结果
        QueryWrapper<HealthTestResult> healthTestResultQueryWrapper = new QueryWrapper<>();
        healthTestResultQueryWrapper.eq("ht_id",htId);
        HealthTestResult one = healthTestResultDao.selectOne(healthTestResultQueryWrapper);

        // 2. 将测试结果返回添加到数据库 health_patient_result
        HealthPatientResult healthPatientResult = new HealthPatientResult();
        String id = "PR"+IdUtil.getSnowflakeNextId();
        healthPatientResult.setPrId(id);
        healthPatientResult.setHtId(htId);

        healthPatientResult.setHtTime(new Date());

        HashMap<String, Integer> perMap  = new HashMap<>();
        perMap.put("A", 0);
        perMap.put("B", 0);
        perMap.put("C", 0);
        perMap.put("D", 0);
        HashMap<String, Integer> lastMap = new HashMap<>();
        lastMap.put("A", 0);
        lastMap.put("B", 0);
        lastMap.put("C", 0);
        lastMap.put("D", 0);
        for (int i = 0; i < healthTestDetails.size(); i++) {
            if (i <= 15){
                if ("1".equals(healthTestDetails.get(i).getHtResult())){
                    perMap.compute("A", (k, a) -> a + 1);
                }else if ("2".equals(healthTestDetails.get(i).getHtResult())){
                    perMap.compute("B", (k, a) -> a + 1);
                }else if ("3".equals(healthTestDetails.get(i).getHtResult())){
                    perMap.compute("C", (k, a) -> a + 1);
                } else if ("4".equals(healthTestDetails.get(i).getHtResult())) {
                    perMap.compute("D", (k, a) -> a + 1);
                }
            } else{
                if ("1".equals(healthTestDetails.get(i).getHtResult())){
                    lastMap.compute("A", (k, a) -> a + 1);
                }else if ("2".equals(healthTestDetails.get(i).getHtResult())){
                    lastMap.compute("B", (k, a) -> a + 1);
                }else if ("3".equals(healthTestDetails.get(i).getHtResult())){
                    lastMap.compute("C", (k, a) -> a + 1);
                } else if ("4".equals(healthTestDetails.get(i).getHtResult())) {
                    lastMap.compute("D", (k, a) -> a + 1);
                }
            }
        }
        int red = perMap.get("A") + lastMap.get("D");
        int yellow = perMap.get("B") + lastMap.get("C");
        int blue = perMap.get("C") + lastMap.get("B");
        int green = perMap.get("D") + lastMap.get("A");
        int maxColorValue = Math.max(Math.max(red, yellow), Math.max(blue, green));
        if (maxColorValue == red){
            healthPatientResult.setHtResContent(one.getResA());
            healthPatientResult.setHtResTitle(one.getATitle());
        } else if (maxColorValue == yellow) {
            healthPatientResult.setHtResContent(one.getResB());
            healthPatientResult.setHtResTitle(one.getBTitle());
        } else if (maxColorValue == blue) {
            healthPatientResult.setHtResContent(one.getResC());
            healthPatientResult.setHtResTitle(one.getCTitle());
        } else {
            healthPatientResult.setHtResContent(one.getResD());
            healthPatientResult.setHtResTitle(one.getDTitle());
        }
        //
        healthPatientResult.setPatientId(patient.getPatientId());
        healthPatientResultDao.insert(healthPatientResult);
        // 3. 将测试结果添加到数据库  health_patient_result_item
        for(HealthTestDetail testResult : healthTestDetails){
            HealthPatientResultItem healthPatientResultItem =
                    new HealthPatientResultItem(null,patient.getPatientId(),testResult.getId(),null,id);
            if ("1".equals(testResult.getHtResult())){
                healthPatientResultItem.setResult(testResult.getQuestionA());
            } else if ("2".equals(testResult.getHtResult())) {
                healthPatientResultItem.setResult(testResult.getQuestionB());
            } else if ("3".equals(testResult.getHtResult())) {
                healthPatientResultItem.setResult(testResult.getQuestionC());
            } else if ("4".equals(testResult.getHtResult())) {
                healthPatientResultItem.setResult(testResult.getQuestionD());
            }
            healthPatientResultItemDao.insert(healthPatientResultItem);
        }
        GetTestResultVo getTestResultVo = new GetTestResultVo();
        getTestResultVo.setTestResultTitle(healthPatientResult.getHtResTitle());
        getTestResultVo.setTestResult(healthPatientResult.getHtResContent());
        return new R<>(200, "查询成功", getTestResultVo);
    }
    /**
     * @create by: Zr
     * @description: 查看该患者的所有的健康测试的结果，用户信息来源为redis,分页信息来源于前端
     * @create time: 2025/4/24 15:55
     * @param patient
     * @param current
     * @param size
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.HealthPatientResult>>
     */
    @Override
    public R<Page<HealthPatientResult>> getTestHistory(HisPatient patient, Integer current, Integer size) {
        // 1. 查询该患者的所有的健康测试的结果
        QueryWrapper<HealthPatientResult> healthPatientResultQueryWrapper = new QueryWrapper<>();
        healthPatientResultQueryWrapper.eq("patient_id",patient.getPatientId());
        // 2. 分页信息
        Page<HealthPatientResult> healthPatientResultPage = new Page<>(current,size);
        // 3. 查询
        Page<HealthPatientResult> page = healthPatientResultDao.selectPage(healthPatientResultPage, healthPatientResultQueryWrapper);
        return new R<>(200, "查询成功", page);
    }
}
